06. Webpack and Sass
Installing Loaders
So now for the webpack portion of all of this. Like we talked about earlier, we are going to use webpack loaders to turn our sass into css. First let’s install all the tools we’ll need:
npm i -D style-loader node-sass css-loader sass-loader
Then add this test case to the rules array in your dev webpack config.
{
test: /\.scss$/,
use: [ 'style-loader', 'css-loader', 'sass-loader' ]
}
FEND C4 L3 A03 WEBPACK AND SASS
Quiz
SOLUTION:
we aren't importing the sass files as a dependencyWhat Went Wrong
Well, if you think back to how we got the javascript files into our main.js, we are missing one of those steps for our css. Really, there are three things you have to do to use webpack loaders. You have to:
- install the loader
- call the loader in the webpack config while targeting the correct file extensions
- require the files in index.js
And there you have it. We have all this lovely sass code, but we never tell webpack that it is required. And because of the dependency tree that webpack builds, if nothing ever requires a file, it’s as if it doesn’t exist.
So, to fix that, let’s go to client/index.js.
Because of css-loader, we can add some lines like this:
import './styles/resets.scss'
This time check the main.js for some of our sass styles, and they should just be there!
Next Steps
Now, one thing that might feel awkward, is that all of our css styles are being run through our main.js. Webpack natively only understands javascript, so it makes sense that until we tell it to do otherwise, it turns everything into javascript by default. Now, this isn’t a problem for development mode necessarily, but it can cause styles to load a split second after content on the server, so we are going to have to clean that up for production mode later on.
Quiz
SOLUTION:
three, two, oneInterview Question
QUESTION: Interview Question
Explain the practice of chaining loaders in webpack. What is the value of this webpack feature, how is it implemented, etc..
ANSWER:
Thanks for your response!
Webpack and Sass Conclusion
We know enough sass to be dangerous, and we can add it to a webpack project. We got a little more practice with loaders and learned that they can be a lot more helpful when chained together than just by themselves.
There are so many more things that you can do with loaders that we just don’t have time to go into. Some of these things include:
- Loading images
- Working in typescript or other languages that compile to javascript
- Working with third party style and js libraries like Bootstrap or Material